package com.genntii.examManager.controller;

import com.genntii.examManager.common.constant.CommonConstant;
import com.genntii.examManager.common.result.Result;
import com.genntii.examManager.domain.dto.UserLoginDTO;
import com.genntii.examManager.domain.dto.UserRegisterDTO;
import com.genntii.examManager.domain.dto.UserUpdateDTO;
import com.genntii.examManager.domain.vo.UserLoginVO;
import com.genntii.examManager.service.UserSecurityService;
import com.genntii.examManager.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserSecurityService userSecurityService;

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result<UserLoginVO> register(@RequestBody UserRegisterDTO user){
        return Result.success(userSecurityService.register(user.getMail(), user.getUsername(), user.getPassword(), user.getCaptcha()));
    }

    @PostMapping("/register/teacher")
    public Result<UserLoginVO> register4t(@RequestBody UserRegisterDTO user){
        return Result.success(userSecurityService.register4t(user.getMail(), user.getUsername(), user.getPassword(),user.getCaptcha()));
    }

    @GetMapping("/sendCaptcha")
    public Result sendCaptcha(@RequestParam("mail") String mail){
        userSecurityService.sendMailCaptcha(mail);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO user){
        return Result.success(userSecurityService.login(user.getLoginCredentials(),user.getPassword()));
    }

    @PutMapping
    public Result<UserLoginVO> update(@RequestBody UserUpdateDTO userUpdateDTO,
                         HttpServletRequest request){
        Long userId = request.getAttribute(CommonConstant.USER_ID) != null ? Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.USER_ID))) : Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.TEACHER_ID)));
        return Result.success(userService.updateBasicInformation(userUpdateDTO,userId));
    }

    @PostMapping("/fileUpload")
    public Result<String> upload(@RequestPart("file") MultipartFile file){
        return Result.success(userService.upload(file));
    }

}
